/*
 * Copyright (c) 2012 RTCLab
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 */

package com.rtckit {

import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.SampleDataEvent;
import flash.utils.ByteArray;
	
public class DTMFPlayer {
	private var sound:Sound = null;
	private var channel:SoundChannel = null;
	private var frequency1:int = 0;
	private var frequency2:int = 0;

	public function DTMFPlayer(freq1:int, freq2:int) {
		frequency1 = freq1;
		frequency2 = freq2;	
	}
	
	public function stop():void {
		if (channel)
			channel.stop();
		channel = null;
		if (sound)
			sound.removeEventListener(SampleDataEvent.SAMPLE_DATA, addSoundBytesToSound);
		sound = null;
	}
	
	public function play():void {
		stop();
		sound = new Sound();
		sound.addEventListener(SampleDataEvent.SAMPLE_DATA, addSoundBytesToSound);
		channel = sound.play();
	}
	
	private function addSoundBytesToSound(event:SampleDataEvent):void {
		var sample1:Number = 0;
		var sample2:Number = 0;
		var sample:Number = 0;
		for (var i:int = 0; i < 4096; i++) {
			sample1 = Math.sin((i + event.position) * 2 * Math.PI / 44100 * frequency1) * 0.5;
			sample2 = Math.sin((i + event.position) * 2 * Math.PI / 44100 * frequency2) * 0.5;
			sample = (sample1 + sample2) / 2;
			event.data.writeFloat(sample);
			event.data.writeFloat(sample);
		}
		if (event.position > 100)
			stop();
	}
}
	
}
